const DB = require('../../../../utils/db')
// 引入jwt token工具
const JwtUtil = require('../../../../utils/jwt')

/**
 * Post
 * 点赞/取消点赞
 */
module.exports = async (ctx) => {
  // 获取token
  let token = ctx.request.header.authorization
  let jwt = new JwtUtil(token)
  // 用token获取到userid
  let userId = jwt.verifyToken()
  // 传递参数
  let params = ctx.request.body
  // 帖子id
  let id = params.dynamicId

  let res = await DB.query(
    `select userid, createTime, label, textContent, imgUrl, title, id, commentTotal, heartId from  dynamic where id = ${id}`
  )
  // 说明点赞的人中不包括当前登录的用户，它是想点赞的
  let heartId = res[0].heartId
  // true表示点赞， false表示取消点赞
  let isHeart = true
  let indexIn
  let arr
  if (heartId !== null) {
    heartId.split(',').forEach(function (item, index) {
      if (item === userId) {
        isHeart = false
        indexIn = index
      }
    })
    arr = heartId.split(',')
  } else {
    arr = []
  }

  if (isHeart) {
    arr.push(userId)
  } else {
    arr.splice(indexIn, 1)
  }

  // 更新到表中
  let updateString = arr.toString()
  // 第一次会把['']当做一个人，所以如果''空，就直接传null到数据库
if (arr.toString()){
  await DB.query(
    `update dynamic set heartId = '${updateString}' where id = ${id}`
  )
}else{
    await DB.query(
      `update dynamic set heartId = null where id = ${id}`
    )
}


  let response
  if (isHeart) {
    response = {
      code: 0,
      mes: '点赞成功',
    }
  } else {
    response = {
      code: 0,
      mes: '取消点赞成功',
    }
  }
  ctx.body = response
}
